//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ttjj.entity.navi;

import com.ttjj.common.Constants;
import com.ttjj.entity.map.Coordinate;
import com.ttjj.entity.map.Position;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 距离处理类
 */
@Data
@EqualsAndHashCode
@Slf4j
public class DistanceResult {
    protected final Coordinate beginCod;
    protected final Coordinate endCod;
    protected final List<Position> passBys = new ArrayList();
    protected int stepCost = 0;

    public DistanceResult(Coordinate beginCod, Coordinate endCod) {
        this.beginCod = beginCod;
        this.endCod = endCod;
    }

    public void compute(int speed) {
        Position beginPos = this.beginCod.toPosition();
        Position endPos = this.endCod.toPosition();
        if (!beginPos.equals(endPos)) {
            TerrainNaviRoute route = TerrainNaviMap.getEffectiveRoute(beginPos, endPos);
            if (route == null) {
                log.error("未获取到{} 到 {} 路径,无法计算花费", beginPos, endPos);
                return;
            }
            this.passBys.addAll(route.getPassBys(beginPos));
            if (this.passBys.size() > 2) {
                int distance = route.getTotalCost() - Constants.getCommonLen() * 2;
                this.stepCost += distance / speed + (distance % speed == 0 ? 0 : 1);
                Coordinate secondPosCod = this.passBys.get(1).toCoordinate();
                this.stepCost += this.getManhattan(this.beginCod, secondPosCod, speed);
                Coordinate lastSecondPosCod = this.passBys.get(this.passBys.size() - 2).toCoordinate();
                this.stepCost += this.getManhattan(lastSecondPosCod, this.endCod, speed);
            } else {
                this.stepCost = this.getManhattan(this.beginCod, this.endCod, speed);
            }
        } else {
            this.stepCost = this.getManhattan(this.beginCod, this.endCod, speed);
        }

    }

    private int getManhattan(Coordinate beginCod, Coordinate endCod, int speed) {
        int distanceX = Math.abs(endCod.getX() - beginCod.getX());
        int distanceY = Math.abs(endCod.getY() - beginCod.getY());
        int result = 0;
        result += distanceX / speed + (distanceX % speed == 0 ? 0 : 1);
        result += distanceY / speed + (distanceY % speed == 0 ? 0 : 1);
        return result;
    }
}
